package com.shurdroides.proyectofinal.activities;


import org.apache.http.auth.AuthenticationException;

import com.shurdroides.proyectofinal.R;
import com.shurdroides.proyectofinal.R.layout;
import com.shurdroides.proyectofinal.server.HttpUtils;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountsException;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class AccountList extends ListActivity {
	private AccountManager accountManager;
	private Intent intent;
	private Account[] accounts;
	private Account selected;
	private Context ctx;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ctx = this;
		setContentView(R.layout.account_list);
		accountManager = AccountManager.get(getApplicationContext());
		accounts = accountManager.getAccountsByType("com.google");
		String[] accountList = new String[accounts.length];

		for (int i = 0; i < accounts.length; i++) {
			accountList[i] = accounts[i].name;
		}
		this.setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, android.R.id.text1,
				accountList));
	}


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		selected = accounts[position];
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					HttpUtils.getAuthenticatedContext(ctx, selected);
					
				} catch (AuthenticationException e) {
					Log.e("AccountListActivity", "AuthenticationException");
				} catch (AccountsException e) {
					Log.e("AccountListActivity", "AccountsException");
				}
				Log.e("AccountList", "OK");
				AccountList.this.finish();
			}
		}).start();
	}
}